//
//  SISSTestTabBarController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2017/10/26.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSTabBarController.h"

#import "SISSBaseViewController.h"
#import "SISSNavigationController.h"
#import "AppDelegate.h"
#import "UITabBar+Badge.h"

#import "zhFullView.h"
#import <zhPopupController/zhPopupController.h>

#import "SISSHouseNumVerifyViewController.h"
#import "SISSHouseEnrollFirstViewController.h"
#import "SISSPassengerResourceEnrollViewController.h"
#import "SISSHouseResourceCooperationViewController.h"
#import "SISSPassengerResourceCooperationViewController.h"
//#import "SISSEnrollPropertyCheckViewController.h"
#import "SISSTenantEnrollViewController.h"
#import "SISSKPIEnrollViewController.h"
#import "SISSLoginViewController.h"
#import "SISSChangePasswordViewController.h"
#import <AudioToolbox/AudioToolbox.h>

// 引入环信头文件
#import <Hyphenate/Hyphenate.h>
#import <UserNotifications/UserNotifications.h>
// 本地通知信息
#import <EaseUI/EaseConvertToCommonEmoticonsHelper.h>
#import <EaseUI/EaseEmotionManager.h>

#import "SISSNetworkingManager+Message.h"
#import "SISSNetworkingManager+Mine.h"

#import <JPUSHService.h>

//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;
@interface SISSTabBarController ()<UINavigationControllerDelegate,EMClientDelegate,EMChatManagerDelegate>

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

/* isFirst */
@property (assign, nonatomic) BOOL isFirst;

@end

@implementation SISSTabBarController

- (instancetype)init{
    if (self = [super init]) {
        
        [self setupUI];
        
        // 判断是否加载新特性或欢迎视图
//        if ([WBUserAccount shared].isLogin) {
//
//            [self setupNewFeatureOrWelcome];
//        }
    }
    
    return self;
}

//- (void)setupNewFeatureOrWelcome {
//
//    BOOL isNew = [NSBundle isNewVersion];
//    if (isNew) {
//        WBNewFeatureView *newFeatureView = [[WBNewFeatureView alloc] init];
//        [self.view addSubview:newFeatureView];
//
//    } else {
//        WBWelComeView *welcomeView = [[WBWelComeView alloc] init];
//        [self.view addSubview:welcomeView];
//    }
//
//}

+ (instancetype)shareInstance {
    
    static SISSTabBarController *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SISSTabBarController alloc] init];
    });
    NSInteger selectedIndex = instance.selectedIndex;
    instance = [[SISSTabBarController alloc] init];
    instance.selectedIndex = selectedIndex;
    return instance;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置别名
    [JPUSHService setAlias:[NSString stringWithFormat:@"%@",[SISSUserAccount shared].spId] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
        NSLog(@" %zd…%@===%zd" ,iResCode,iAlias,seq);
        
    } seq:1];
    
    [[SISSPublicSingleton shared] addObserver:self forKeyPath:@"unreadCount" options:NSKeyValueObservingOptionNew context:NULL];
    
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
    [self requestPeronInfo];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setBadgeCount];
}

#pragma mark - 获取个人信息
- (void)requestPeronInfo {
    
    [SISSPublicSingleton shared].isHud = YES;
    [kNetworkManager requestPersonInfoWithSpId:[SISSUserAccount shared].spId success:^(SISSPersonInfoModel *personInfo) {
        
        [SISSUserAccount shared].portrait = personInfo.portrait;
        [SISSUserAccount shared].name = personInfo.name;
        [SISSUserAccount shared].license_no = personInfo.license_no;
        [SISSUserAccount shared].idNo = personInfo.idNo;
        [SISSUserAccount shared].starLevel = personInfo.star_level;
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

- (void)setBadgeCount {
    
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += [conversation unreadMessagesCount];
    }
    [SISSPublicSingleton shared].unreadCount = unreadCount;
    
}

#pragma mark - 收到消息时的处理
- (void)messagesDidReceive:(NSArray *)aMessages {
    
    [self setBadgeCount];
    
    for (EMMessage *message in aMessages) {
        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        
        switch (state) {
            case UIApplicationStateActive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateInactive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateBackground:
                [self showNotificationWithMessage:message];
                break;
            default:
                break;
        }
        
    }
}

- (void)playSoundAndVibration {
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    // 系统声音
    AudioServicesPlaySystemSound(1007);
    // 收到消息时，震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
}

- (void)showNotificationWithMessage:(EMMessage *)message {
    
    // 提醒，可以根据需要进行弹出，比如显示消息详情，或者是显示“您有一条新消息”
    EMMessageBody *messageBody = message.body;
    NSString *messageStr = @"";
    switch (messageBody.type) {
        case EMMessageBodyTypeImage:{
            messageStr = NSLocalizedString(@"[图片]", @"[image]");
        } break;
        case EMMessageBodyTypeText:{
            // 表情映射。
            NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                        convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
            messageStr = didReceiveText;
            if ([message.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                messageStr = @"[动画表情]";
            }
        } break;
        case EMMessageBodyTypeVoice:{
            messageStr = NSLocalizedString(@"[语音]", @"[voice]");
        } break;
        case EMMessageBodyTypeLocation: {
            messageStr = NSLocalizedString(@"[位置]", @"[location]");
        } break;
        case EMMessageBodyTypeVideo: {
            messageStr = NSLocalizedString(@"[视频]", @"[video]");
        } break;
        case EMMessageBodyTypeFile: {
            messageStr = NSLocalizedString(@"[文件]", @"[file]");
        } break;
        default: {
        } break;
    }
    
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
    BOOL playSound = NO;
    if (!self.lastPlaySoundDate || timeInterval >= kDefaultPlaySoundInterval) {
        self.lastPlaySoundDate = [NSDate date];
        playSound = YES;
    }
    
    //发送本地推送
    if (NSClassFromString(@"UNUserNotificationCenter")) { // ios 10
        // 设置触发时间
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.badge = @([SISSPublicSingleton shared].unreadCount);
        if (playSound) {
            content.sound = [UNNotificationSound defaultSound];
        }
        
        content.body = messageStr;
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.messageId content:content trigger:trigger];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
        
    } else {
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate date]; //触发通知的时间
        notification.alertBody = messageStr;
        notification.alertAction = @"Open";
        notification.timeZone = [NSTimeZone defaultTimeZone];
        if (playSound) {
            notification.soundName = UILocalNotificationDefaultSoundName;
        }
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"unreadCount"]) {
        if ([SISSPublicSingleton shared].unreadCount != 0) {
            self.tabBar.badge = [SISSPublicSingleton shared].unreadCount;
            
            [self.tabBar showBadgeOnMessage];
            
        } else {
            [self.tabBar hideBadgeOnMessage];
        }
        [UIApplication sharedApplication].applicationIconBadgeNumber = [SISSPublicSingleton shared].unreadCount;
        NSLog(@"==== %zd",[SISSPublicSingleton shared].unreadCount);
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


/**
 在dealloc中取消监听
 */
- (void)dealloc {
    
    [[SISSPublicSingleton shared] removeObserver:self forKeyPath:@"unreadCount"];
}

#pragma mark - 当前登录账号在其它设备登录时会接收到该回调
- (void)userAccountDidLoginFromOtherDevice {
    
    if (!self.isFirst) { // 只让此调用一次
        self.isFirst = YES;
        [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
            NSLog(@"rescode: %ld, \ntags: %@, \nalias: %@\n", (long)iResCode, @"tag" , iAlias);
            
        } seq:1];
    }
    [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
        NSLog(@"EMLogout : %@",aError);
    }];
    NSString *str = @"您的帐户在另一端登录，您已被迫下线。如非本人操作请立即修改密码！";
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentLeft;
    
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16], NSForegroundColorAttributeName: COLOR(0x334A60), NSParagraphStyleAttributeName: paragraphStyle}];
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alertC setValue:attr forKey:@"attributedMessage"];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"修改密码" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        SISSChangePasswordViewController *changePSDVC = [[SISSChangePasswordViewController alloc] init];
        changePSDVC.url = URL_CHANGE_PASSWORD;
        SISSNavigationController *nav = [[SISSNavigationController alloc] initWithRootViewController:changePSDVC];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav animated:YES completion:nil];
        NSLog(@"修改密码");
    }];
    if (iOS9Later) { // 适配iOS8
        // 修改按钮
        [cancelAction setValue:COLOR(0x74A4FE) forKey:@"titleTextColor"];
    }
    
    [alertC addAction:cancelAction];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [UIApplication sharedApplication].keyWindow.rootViewController = [[SISSLoginViewController alloc] init];
        NSLog(@"重新登录");
    }];
    [alertC addAction:okAction];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertC animated:YES completion:nil];
}


#pragma mark - 初始化
- (void)setupUI{
    
    // 获取URL
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"main.json" withExtension:nil];
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    // 反序列化
    NSArray *dictArr = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
    NSMutableArray *controllers = [NSMutableArray arrayWithCapacity:dictArr.count];
    
    // 遍历创建控制器,添加到数组中
    for (NSDictionary *dict in dictArr) {
        
        SISSBaseViewController *viewController = (SISSBaseViewController *)[self getControllerWithClsName:dict[@"clsName"] title:dict[@"title"] imageName:dict[@"imageName"] visitorInfoDictionary:dict[@"visitorInfo"]];
        
        [controllers addObject:viewController];
    }
    
    self.viewControllers = controllers;
    [self addComposeButton];
    
}



/**
 传入类名,title,imageName创建控制器
 
 @param clsName 类名
 @param title title
 @param imageName imageName
 @return 控制器
 */
- (UIViewController *)getControllerWithClsName:(NSString *)clsName title:(NSString *)title imageName:(NSString *)imageName visitorInfoDictionary:(NSDictionary *)visitorInfoDictionary{
    
    // 根据类型加载类
    Class cls = NSClassFromString(clsName);
    SISSBaseViewController *viewController = [[cls alloc] init];
    
    // 断言
    NSAssert([viewController isKindOfClass:[SISSBaseViewController class]], @"类名不是一个正确的控制器类名");
    if ([title isEqualToString:@"我的"]) {
        UIStoryboard *mineStoryboard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
        viewController = [mineStoryboard instantiateInitialViewController];
    }
    
    
    SISSNavigationController *navigationController = [[SISSNavigationController alloc] initWithRootViewController:viewController];
    
    // 配置文字
    viewController.title = title;
//    viewController.visitorInfoDictory = visitorInfoDictionary;
    
    // 设置选中时的字体大小和颜色
    [navigationController.tabBarItem setTitleTextAttributes:@{
//                                                              NSFontAttributeName : [UIFont systemFontOfSize:14],
                                                              NSForegroundColorAttributeName : MAIN_COLOR
                                                              
                                                              }forState:UIControlStateSelected];
    
    // 配置图片
    UIImage *normalImage =[UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]];
    UIImage *selectedImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_sel",imageName]];
    
    navigationController.tabBarItem.image = [normalImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    navigationController.tabBarItem.selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    return navigationController;
}


/**
 添加composeButton
 */
- (void)addComposeButton{
    
    UIButton *composeButton = [[UIButton alloc] init];
    [self.tabBar addSubview:composeButton];
    
    NSInteger count = self.childViewControllers.count;
    // 将按钮的内缩进的宽度减少
    CGFloat w = self.tabBar.bounds.size.width / count - 1;
    
    // CGRectInset 正数内向缩进,负数外向扩展
    composeButton.frame = CGRectInset(self.tabBar.bounds, w * 2, 0);
    
    // 设置图片
    [composeButton setImage:[UIImage imageNamed:@"tab_add"] forState:UIControlStateNormal];
    [composeButton setImage:[UIImage imageNamed:@"tab_add_sel"] forState:UIControlStateHighlighted];
    
    // 设置背景
//    [composeButton setBackgroundImage:[UIImage imageNamed:@"tab_add_bg"] forState:UIControlStateNormal];
//    [composeButton setBackgroundImage:[UIImage imageNamed:@"tab_add_bg"] forState:UIControlStateHighlighted];
    
    //    [composeButton sizeToFit];
    
    // 设置frame
    composeButton.center = CGPointMake(self.tabBar.center.x, self.tabBar.bounds.size.height * 0.5);
    
    // 添加点击事件
    [composeButton addTarget:self action:@selector(composeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - composeButton的点击事件
- (void)composeButtonAction:(UIButton *)composeButton {
    zhFullView *full = [self fullView];
    full.didClickFullView = ^(zhFullView * _Nonnull fullView) {
        [self.zh_popupController dismiss];
    };
    
    full.didClickItems = ^(zhFullView *fullView, NSInteger index) {
        
        self.zh_popupController.didDismiss = ^(zhPopupController * _Nonnull popupController) {
            
            // 跳转不同的控制器
            SISSNavigationController *navc;
            switch (index) {
                case 0: {
                    SISSHouseNumVerifyViewController *vc = [[SISSHouseNumVerifyViewController alloc] init];
//                    SISSHouseEnrollFirstViewController *vc = [[SISSHouseEnrollFirstViewController alloc] init];
                    vc.title = @"房源登记";
                    vc.isRegistration = YES;
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 1: {
                    SISSPassengerResourceEnrollViewController *vc = [[SISSPassengerResourceEnrollViewController alloc] init];
                    vc.title = @"客源登记";
                    vc.isRegistration = YES;
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 2: {
                    SISSHouseResourceCooperationViewController *vc = [[SISSHouseResourceCooperationViewController alloc] init];
                    vc.title = @"房源合作";
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 3: {
                    SISSPassengerResourceCooperationViewController *vc = [[SISSPassengerResourceCooperationViewController alloc] init];
                    vc.title = @"客源合作";
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 4: {
//                    SISSEnrollPropertyCheckViewController *vc = [[SISSEnrollPropertyCheckViewController alloc] init];
                    SISSHouseEnrollFirstViewController *vc = [[SISSHouseEnrollFirstViewController alloc] init];
                    vc.title = @"出租登记";
                    vc.isRentOut = YES;
                    vc.isRegistration = YES;
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 5: {
                    SISSTenantEnrollViewController *vc = [[SISSTenantEnrollViewController alloc] init];
                    vc.title = @"租客登记";
                    vc.isRegistration = YES;
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 6: {
                    SISSKPIEnrollViewController *vc = [[SISSKPIEnrollViewController alloc] init];
                    vc.title = @"业绩指标申报";
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                default:
                    break;
            }
            
            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            navc.modalPresentationStyle = UIModalPresentationFullScreen;
            [delegate.window.rootViewController presentViewController:navc animated:YES completion:nil];
            
        };
        
        [fullView endAnimationsCompletion:^(zhFullView *fullView) {
            [self.zh_popupController dismiss];
        }];
    };
    self.zh_popupController = [zhPopupController popupControllerWithMaskType:zhPopupMaskTypeWhiteBlur];
    self.zh_popupController.allowPan = YES;
    [self.zh_popupController presentContentView:full];
}

#pragma mark - 点击＋弹出的UI
- (zhFullView *)fullView {
    zhFullView *fullView = [[zhFullView alloc] initWithFrame:self.view.frame];
    NSArray *array = @[@"1", @"2", @"3", @"4", @"5", @"6", @"7"];
    NSArray *titleNames = @[@"房源登记", @"客源登记", @"房源合作", @"客源合作", @"出租登记", @"租客登记", @"业绩指标申报"];
    NSMutableArray *models = [NSMutableArray arrayWithCapacity:array.count];
    for (NSString *string in array) {
        zhIconLabelModel *item = [zhIconLabelModel new];
        item.icon = [UIImage imageNamed: string];
        item.text = titleNames[[string integerValue] - 1];
        [models addObject:item];
    }
    fullView.models = models;
    return fullView;
}


@end
